package MEET.src.View;

import MEET.src.code.Meeting;
import MEET.src.code.UserDao;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.List;

public class UserReservationsFrame extends JFrame {
    private String userId;
    private JTable reservationsTable;
    private DefaultTableModel tableModel;
    private JPanel contentPane;

    public UserReservationsFrame(String userId) {
        this.userId = userId;
        initComponents();
        loadReservations();
    }

    private void initComponents() {
        setTitle("上海电力大学会议预订系统 - 我的预订");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(900, 600);
        setLocationRelativeTo(null);

        // 主面板设置
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 5));
        setContentPane(contentPane);

        // 1. 顶部标题栏
        createHeaderPanel();

        // 2. 内容区
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.setBorder(new EmptyBorder(15, 15, 15, 15));
        mainPanel.setBackground(new Color(240, 245, 249));

        // 内部标题
        JPanel innerTitlePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        innerTitlePanel.setBackground(new Color(240, 245, 249));
        JLabel innerTitle = new JLabel("我的会议预订");
        innerTitle.setFont(new Font("微软雅黑", Font.BOLD, 18));
        innerTitle.setForeground(new Color(0, 125, 153));
        innerTitlePanel.add(innerTitle);
        mainPanel.add(innerTitlePanel, BorderLayout.NORTH);

        // 表格模型
        tableModel = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 表格不可编辑
            }
        };
        tableModel.addColumn("会议ID");
        tableModel.addColumn("会议名称");
        tableModel.addColumn("地点");
        tableModel.addColumn("会议室");
        tableModel.addColumn("开始时间");
        tableModel.addColumn("结束时间");
        tableModel.addColumn("状态");

        reservationsTable = new JTable(tableModel);
        reservationsTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        reservationsTable.setRowHeight(30);
        reservationsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        reservationsTable.setGridColor(new Color(220, 220, 220));
        reservationsTable.setShowGrid(true);
        reservationsTable.setIntercellSpacing(new Dimension(0, 0));
        reservationsTable.setFillsViewportHeight(true);

        // 设置表头样式
        JTableHeader header = reservationsTable.getTableHeader();
        header.setFont(new Font("微软雅黑", Font.BOLD, 14));
        header.setBackground(new Color(70, 130, 180));
        header.setForeground(Color.WHITE);
        header.setReorderingAllowed(false);

        // 设置表格列宽
        reservationsTable.getColumnModel().getColumn(0).setPreferredWidth(70);  // 会议ID
        reservationsTable.getColumnModel().getColumn(1).setPreferredWidth(180); // 会议名称
        reservationsTable.getColumnModel().getColumn(2).setPreferredWidth(120); // 地点
        reservationsTable.getColumnModel().getColumn(3).setPreferredWidth(100); // 会议室
        reservationsTable.getColumnModel().getColumn(4).setPreferredWidth(180); // 开始时间
        reservationsTable.getColumnModel().getColumn(5).setPreferredWidth(180); // 结束时间
        reservationsTable.getColumnModel().getColumn(6).setPreferredWidth(90);  // 状态

        // 设置状态列渲染器
        reservationsTable.getColumnModel().getColumn(6).setCellRenderer(new StatusRenderer());

        JScrollPane scrollPane = new JScrollPane(reservationsTable);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
        scrollPane.setBackground(Color.WHITE);
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setBorder(new EmptyBorder(10, 0, 5, 0));
        buttonPanel.setBackground(new Color(240, 245, 249));
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 5));

        // 刷新按钮
        JButton refreshButton = createStyledButton("刷新", new Color(70, 130, 180));
        refreshButton.addActionListener(e -> loadReservations());
        buttonPanel.add(refreshButton);

        // 取消预订按钮
        JButton cancelButton = createStyledButton("取消预订", new Color(220, 20, 60));
        cancelButton.addActionListener(e -> cancelReservation());
        buttonPanel.add(cancelButton);

        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        contentPane.add(mainPanel, BorderLayout.CENTER);
    }

    private void createHeaderPanel() {
        JPanel headerPanel = new JPanel();
        headerPanel.setBackground(new Color(0, 125, 153));
        headerPanel.setPreferredSize(new Dimension(100, 50));

        JLabel lblTitle = new JLabel("上海电力大学会议预订系统");
        lblTitle.setForeground(Color.WHITE);
        lblTitle.setFont(new Font("微软雅黑", Font.BOLD, 20));

        headerPanel.add(lblTitle);
        contentPane.add(headerPanel, BorderLayout.NORTH);
    }

    private JButton createStyledButton(String text, Color bgColor) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 14));
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(bgColor.darker(), 1),
                BorderFactory.createEmptyBorder(8, 20, 8, 20)
        ));
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 添加悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(bgColor.brighter());
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(bgColor);
            }
        });

        return button;
    }

    private void loadReservations() {
        // 清空现有数据
        tableModel.setRowCount(0);

        // 从数据库加载预订
        List<Meeting> reservations = UserDao.getUserReservations(userId);

        // 填充表格
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (Meeting meeting : reservations) {
            tableModel.addRow(new Object[]{
                    meeting.getMID(),
                    meeting.getMname(),
                    meeting.getLocation(),
                    meeting.getRoom(),
                    dateFormat.format(meeting.getMstarttime()),
                    dateFormat.format(meeting.getMendtime()),
                    meeting.getStatus()
            });
        }
    }

    private void cancelReservation() {
        int selectedRow = reservationsTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要取消的预订", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        String meetingId = (String) tableModel.getValueAt(selectedRow, 0);
        String meetingName = (String) tableModel.getValueAt(selectedRow, 1);

        int confirm = JOptionPane.showConfirmDialog(
                this,
                "确定要取消会议 '" + meetingName + "' 的预订吗？",
                "确认取消",
                JOptionPane.YES_NO_OPTION);

        if (confirm == JOptionPane.YES_OPTION) {
            if (UserDao.cancelReservation(meetingId)) {
                JOptionPane.showMessageDialog(this, "预订已取消");
                loadReservations(); // 刷新列表
            } else {
                JOptionPane.showMessageDialog(this, "取消失败", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    // 自定义状态列渲染器
    private static class StatusRenderer extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus, int row, int column) {
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if ("已预订".equals(value)) {
                c.setForeground(new Color(0, 100, 0)); // 绿色
                c.setFont(c.getFont().deriveFont(Font.BOLD));
            } else if ("已取消".equals(value)) {
                c.setForeground(new Color(139, 0, 0)); // 深红色
            } else {
                c.setForeground(Color.BLACK);
            }
            setHorizontalAlignment(SwingConstants.CENTER);
            return c;
        }
    }
}